package com.zzyl.nursing.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.jwt.Claims;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.WeChatUtils;
import com.zzyl.common.wx.WeChatLoginProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WeChatLoginProperties weChatLoginProperties;

    @Override
    public AjaxResult login(UserLoginRequestDto dto) {
        //1.调用微信的登录接口
        String openId = getOpenId(dto);
        //2.根据openId查询数据库，判断是否已经注册
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        if (familyMember == null) {
            familyMember = new FamilyMember();
            //新用户(把openId设置进去)
            familyMember.setOpenId(openId);
        }
        //3.调用微信接口获取 调用凭证
        String weChatToken = getWeChatToken();
        //4.请求微信接口获取手机号信息
        String phoneNumber = getPhoneNumber(dto, weChatToken);
        //5.进行更新或新增操作
        insertOrUpdate(dto, familyMember, phoneNumber);
        //6.生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());
        String token = tokenService.createToken(claims);
        //7.封装数据
        return AjaxResult.success(LoginVo.builder()
                .nickName(familyMember.getName())
                .token(token)
                .build());


    }

    /**
     * 新增或者删除操作
     * @param dto
     * @param familyMember
     * @param phoneNumber
     */
    private void insertOrUpdate(UserLoginRequestDto dto, FamilyMember familyMember, String phoneNumber) {
        //截取手机号后四位
        String phone = phoneNumber.substring(phoneNumber.length() - 4);
        familyMember.setName("L." + phone);
        if (familyMember.getId() != null) {
            //说明是老用户，更新数据
            if (!familyMember.getPhone().equals(phoneNumber)) {
                familyMember.setPhone(phoneNumber);
            }
            updateById(familyMember);
        } else {
            //说明是新用户,新增数据
            familyMember.setPhone(phoneNumber);
            save(familyMember);
            //新增后,将id拿过来
            familyMember.setId(familyMember.getId());
        }
    }

    /**
     * 获取手机号
     * @param dto
     * @param weChatToken 调用凭证
     * @return
     */
    private String getPhoneNumber(UserLoginRequestDto dto, String weChatToken) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", dto.getPhoneCode());
        HttpResponse response = HttpUtil.createRequest(Method.POST, WeChatUtils.PHONE_URL + weChatToken)
                .body(JSON.toJSONString(map))
                .execute();
        String resultJsonStr = response.body();
        Map resultMap = JSON.parseObject(resultJsonStr, Map.class);
        Map phongMap = (Map) resultMap.get("phone_info");
        String phoneNumber = (String) phongMap.get("phoneNumber");
        return phoneNumber;
    }

    /**
     * 获取调用凭证
     * @return
     */
    private String getWeChatToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", weChatLoginProperties.getAppId());
        map.put("secret", weChatLoginProperties.getSecret());
        map.put("grant_type", "client_credential");
        String resultJsonStr = HttpUtil.get(WeChatUtils.TOKEN_URL, map);
        Map resultMap = JSON.parseObject(resultJsonStr, Map.class);

        return (String) resultMap.get("access_token");
    }


    /**
     * 获取openId
     * @param dto
     * @return
     */
    private String getOpenId(UserLoginRequestDto dto) {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", weChatLoginProperties.getAppId());
        map.put("secret", weChatLoginProperties.getSecret());
        map.put("js_code", dto.getCode());
        map.put("grant_type", "authorization_code");
        String resultJsonStr = HttpUtil.get(WeChatUtils.OPEN_ID_URL, map);
        Map resultMap = JSON.parseObject(resultJsonStr, Map.class);

        return (String) resultMap.get("openid");
    }
}
